import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:my_desk_flutter/controller/auth_controller.dart';
import 'package:my_desk_flutter/controller/home_tab_controller.dart';
import 'package:my_desk_flutter/page/bus_search_page.dart';
import 'package:my_desk_flutter/page/login_page.dart';
import 'package:my_desk_flutter/page/mine/mine_page.dart';

class HomePage extends ConsumerWidget {
  const HomePage({super.key});

  void initListener(BuildContext context, WidgetRef ref) {
    // 如果退出登录 则自动打开登录页面
    ref.listen(
      authControllerProvider,
      (previous, next) {
        if (next.value?.isAuth != previous?.value?.isAuth) {
          next.when(
            data: (value) {
              if (!value.isAuth) {
                Navigator.of(context).pushNamed('/login');
              }
            },
            error: (_, __) {},
            loading: () {},
          );
        }
      },
    );
  }

  @override
  Widget build(BuildContext context, WidgetRef ref) {
    initListener(context, ref);
    return Scaffold(
      body: _buildMainPage(context, ref),
      bottomNavigationBar: _buildNavigator(context, ref),
    );
  }

  Widget _buildMainPage(BuildContext context, WidgetRef ref) {
    return IndexedStack(
      index: ref.watch(homeTabControllerProvider),
      children: [
        const BusSearchPage(),
        Center(
          child: Text(
            "第二个页面",
            style: TextStyle(
              fontSize: 20,
            ),
          ),
        ),
        Center(
          child: Text(
            "第三个页面",
            style: TextStyle(
              fontSize: 20,
            ),
          ),
        ),
        MinePage(),
      ],
    );
  }

  _buildNavigator(BuildContext context, WidgetRef ref) {
    return SafeArea(
      child: DefaultTabController(
        length: 4,
        child: TabBar(
          // padding: EdgeInsets.symmetric(vertical: 8.w),
          labelPadding: EdgeInsets.symmetric(vertical: 8.w),
          indicator: const BoxDecoration(),
          onTap: (int index) {
            ref.read(homeTabControllerProvider.notifier).toggleIndex(index);
          },
          tabs: const [
            Text("第一"),
            Text("第二"),
            Text("第三"),
            Text("第四"),
          ],
        ),
      ),
    );
  }
}
